import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Input, Label, Image} from '@tarojs/components';
import {AtButton, AtIcon, AtInput, AtModal, AtModalAction, AtModalContent, AtModalHeader} from 'taro-ui';
import {AlipayType, Wallet as WalletData} from '../../utils/server.interface';
import {http} from '../../utils/http';
import {GET_ALIPAY, UPDATE_ALIPAY, WALLET, WITH_DRAW, CONTENT_PLAT_QR, TARO_ENV} from '../../constants/api';
import {user} from '../../utils/user.service'
import {vcmonitor} from "../../utils/tools";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {platform} from "../../utils/platform-settting.service";
import './cash.scss';

type PageState = {
  formData: {
    alipay_no: number
    true_name: string
  }
  wallet: any
  ban: boolean
  showWithdraw: boolean
  submitting: boolean
  uuid: string
  withdraw: number
  qrImg: any
  modalShow: boolean
  alipay: boolean
}
export default class Wallet extends Component {
  state: PageState = {
    formData: {
      alipay_no: 0,
      true_name: '',
    },
    wallet: false,
    ban: false,
    showWithdraw: false,
    submitting: false,
    withdraw: 0,
    uuid: '',
    qrImg: '',
    modalShow: false,
    alipay: true
  }

  async componentDidShow() {
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    this.setState({
      uuid: Taro.getCurrentInstance().router.params.uuid
    })
    if (!isLogin) {
      Taro.showToast({
        title: '登录已失效，请重新登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    //读取下平台设置，看下是什么提现方式
    const data = await platform.getServerSet()
    //如果是使用商户自己的微信支付商户
    if (data.sellerWithdrawalType && data.sellerWithdrawalType === 1) {
      this.setState({alipay: false})
    } else {
      const alipay: any = await http.get<AlipayType>(GET_ALIPAY, {})
      if (alipay && alipay.userAlipay) {
        const formData = {alipay_no: alipay.userAlipay.alipay_no || '', true_name: alipay.userAlipay.true_name || ''}
        this.setState({formData})
        if (!formData.alipay_no && !formData.true_name) {
          this.setState({showWithdraw: true})
        }
      } else {
        this.setState({showWithdraw: true})
      }
    }
    const wallet = await http.get<Wallet>(WALLET, {})
    if (wallet) {
      this.setState({wallet})
    }
  }

  async initData() {
    const alipay: any = await http.get<AlipayType>(GET_ALIPAY, {})
    if (alipay && alipay.userAlipay) {
      const formData = {alipay_no: alipay.userAlipay.alipay_no || '', true_name: alipay.userAlipay.true_name || ''}
      if (!formData.alipay_no && !formData.true_name) {
        this.setState({showWithdraw: true})
      } else {
        this.setState({formData, showWithdraw: false})
      }
    } else {
      this.setState({showWithdraw: true})
    }
  }

  async submitFunc(ban) {
    const {formData} = this.state
    if (!!formData.alipay_no && !!formData.true_name) {
      Taro.showLoading({title: '提交中...'})
      const ret: any = await http.postCondition<boolean>(UPDATE_ALIPAY, formData)
      Taro.hideLoading()
      if (ret.isOk) {
        Taro.showToast({title: '保存成功'})
        await this.initData()
      } else {
        if (ret.msg) {
          return Taro.showToast({title: ret.msg, icon: 'none'})
        }
      }
      this.setState({
        ban: !ban
      })
    } else {
      if (!!formData.alipay_no) {
        Taro.showToast({title: '请填写支付宝账户', icon: 'none', mask: true})
        return
      }
      if (!!formData.true_name) {
        Taro.showToast({title: '请填写支付宝账户', icon: 'none', mask: true})
        return
      }
    }
  }

  async submit() {
    this.setState({submitting: true}, async () => {
      if (this.state.wallet.withdrawBalance < this.state.withdraw) {
        Taro.showToast({title: '超过最大提现金额', icon: 'none'})
        this.setState({submitting: false})
      } else if (this.state.withdraw == 0) {
        Taro.showToast({title: '请输入金额', icon: 'none'})
        this.setState({submitting: false})
      } else if (this.state.withdraw < this.state.wallet.sellerWithdrawMinimumAmount) {
        Taro.showToast({title: '最低提现' + this.state.wallet.sellerWithdrawMinimumAmount + '元', icon: 'none'})
        this.setState({submitting: false})
      } else {
        const ret = await http.postCondition(WITH_DRAW, {amount: this.state.withdraw, uuid: this.state.uuid})
        //蝌蚪才走这个
        if (ret && process.env.P_ENV === 'kd') {
          const res = await http.HGet(CONTENT_PLAT_QR, {send_type: 6});
          this.setState({showWithdraw: false, qrImg: res.data.code, modalShow: true})
        } else {
          if (ret) {
            Taro.showToast({title: '提现成功！' + ret.data, icon: 'none', mask: true, duration: 2000})
            setTimeout(() => {
              Taro.navigateBack({
                delta: 1
              })
            }, 2000)
            this.setState({showWithdraw: false})
          }
        }
        this.setState({submitting: false})
      }
    })
  }

  handleChange(type, value) {
    const {formData} = this.state
    formData[type] = value
    this.setState({})
  }

  inputChange(type, value) {
    const {formData} = this.state
    formData[type] = value.detail.value.replace(/\s*/g, '')
    this.setState({
      formData
    })
  }

  withdrawChange(e) {
    this.setState({
      withdraw: e.detail.value
    })

  }

  setFrom() {
    const {ban} = this.state
    if (ban) {
      this.submitFunc(ban)
    } else {
      this.setState({
        ban: !ban
      })
    }
  }

  closedWithDraw() {
    Taro.navigateBack({
      delta: 1
    })
  }

  handleCancel() {
    this.setState({modalShow: false})
  }

  inputBlur() {
    if (TARO_ENV === 'h5') {
      window.scrollTo(0, 0);
      document.body.scrollTop = document.documentElement.scrollTop = 0;
    }
  }

  render() {
    const {wallet, withdraw, showWithdraw, ban, formData, submitting, qrImg, modalShow, alipay} = this.state
    return (
      <View className='cash-root'>
        <GzhAuth />
        {showWithdraw || ban ?
          <View className='drawer_screen'>
            <View className='drawer_bj' onClick={this.closedWithDraw.bind(this)}>
            </View>
            <View className='drawer_box'>
              <View className='drawer_box_off' onClick={this.closedWithDraw.bind(this)}><AtIcon value='close-circle'
                size='30'
                color='#c0c0c0'
              /></View>
              <View className='drawer_box_title'>
                绑定支付宝账号
              </View>
              <View className='drawer_box_form'>
                <View className='title'>支付宝账号</View>
                <Input className='input' name='alipay_no' type='text' placeholder='请填写支付宝账号'
                  value={String(formData.alipay_no || '')}
                  onBlur={this.inputBlur.bind(this)}
                  onInput={this.inputChange.bind(this, 'alipay_no')}
                />
              </View>
              <View className='drawer_box_form'>
                <View className='title'>真实姓名</View>
                <Input className='input' name='true_name' type='text' placeholder='请填写支付宝账号关联真实姓名'
                  maxLength={15}
                  value={String(formData.true_name || '')}
                  onBlur={this.inputBlur.bind(this)}
                  onInput={this.inputChange.bind(this, 'true_name')}
                />
              </View>
              <View className='drawer_btn' onClick={this.submitFunc.bind(this)}>绑定</View>
            </View>
          </View>
          :
          <View className='cashOut'>
            {alipay && <View className='cashOut-box'>
              <View className='cashOut-box-left'>
                <View className='zfb-info'>
                  <AtInput
                    name='alipay_no'
                    border={false}
                    disabled
                    title='支付宝账户'
                    type='text'
                    onBlur={this.inputBlur.bind(this)}
                    value={formData.alipay_no || ''}
                  />
                  <AtInput
                    name='true_name'
                    border={false}
                    disabled
                    title='真实姓名'
                    onBlur={this.inputBlur.bind(this)}
                    type='text'
                    value={formData.true_name}
                  />
                </View>
              </View>
              <View className='cashOut-box-right' onClick={() => this.setState({ban: !ban})}>修改</View>
            </View>}
            <View className='cashOut-bottom'>
              <View className='drawer_title'>提现金额</View>
              <View className='drawer_content'>
                <View className='top grid'>
                  <Label className='title'>￥</Label>
                  <Input className='Input_base input_h30' name='money' type='digit' value={String(withdraw || '')}
                    onInput={this.withdrawChange.bind(this)}
                    onBlur={this.inputBlur.bind(this)}
                  />
                </View>
                <View className='tx_bezhu'>可提余额 <Text
                  style='font-family: Avenir;'
                >{wallet.withdrawBalance}</Text>, <View className='tx_allTx'
                  onClick={() => {
                                                          this.setState({withdraw: wallet.withdrawBalance})
                                                        }}
                >全部提现</View>{wallet.sellerWithdrawRate > 0 &&
                  <View className='right'>手续费：<Text>￥ {wallet.sellerWithdrawRate}</Text></View>}</View>
              </View>
              <AtButton loading={submitting} disabled={submitting && !!formData.alipay_no && !!formData.true_name}
                type='primary' className='btn_tx' onClick={this.submit.bind(this)}
              >确认提现</AtButton>
            </View>
          </View>}
        <AtModal className='modal_concatWx' isOpened={modalShow} onClose={this.handleCancel.bind(this)}>
          <AtModalHeader>{process.env.fxName}提现审核</AtModalHeader>
          <AtModalContent>
            {qrImg && qrImg !== 'variable_code_close' && <Image
              mode='aspectFill'
              style='width: 120px;height: 120px;'
              src={qrImg}
            />}
          </AtModalContent>
          <AtModalAction>
            {process.env.TARO_ENV === 'h5' && <Text className='modal_txt' style='text-align:center;'>
              您的提现申请已收到<br />请添加财务微信发送“我要提现”
            </Text>}
            {process.env.TARO_ENV !== 'h5' && <Text className='modal_txt'>
              您的提现申请已收到\n请添加财务微信发送“我要提现”
            </Text>}
          </AtModalAction>
        </AtModal>
      </View>
    );
  }
}
